const express = require("express");
const dbOperations = require("./dbOperations");

const app = express();
const port = 3000;

app.use(express.json()); // 解析 JSON 请求体

// 连接到数据库并获取集合
let collection;
dbOperations.connect().then((col) => {
  collection = col;
  console.log("Database and collection ready");
});

// 插入文档
app.post("/vegetables", async (req, res) => {
  try {
    const document = req.body;
    console.log(document);
    const result = await dbOperations.insertDocument(collection, document);
    res.status(201).json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 查询文档
app.get("/vegetables/:name", async (req, res) => {
  try {
    const query = { name: req.params.name };
    const document = await dbOperations.findDocument(collection, query);
    if (document) {
      res.json(document);
    } else {
      res.status(404).json({ message: "Document not found" });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新文档
app.put("/vegetables/:name", async (req, res) => {
  try {
    const filter = { name: req.params.name };
    const update = { $set: req.body };
    const result = await dbOperations.updateDocument(collection, filter, update);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除文档
app.delete("/vegetables/:name", async (req, res) => {
  try {
    const query = { name: req.params.name };
    const result = await dbOperations.deleteDocument(collection, query);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});